package service

import (
	"common/database/config"
	"gorm.io/gorm"
	"project_video_srv/internal/models/dao"
	__ "project_video_srv/proto"
)

func List(request *__.ListRequest) []*dao.Video {
	var video []*dao.Video
	if request.KeyWord != "" {
		config.DB.Where("video_title like ?", "%"+request.KeyWord+"%").
			Scopes(Paginate(int(request.Page), int(request.PageSize))).Find(&video)
		return video
	}
	config.DB.Scopes(Paginate(int(request.Page), int(request.PageSize))).Find(&video)
	return video
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
